package cn.huhst.cas.weisiqian.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import cn.huhst.cas.weisiqian.pojo.COMMENT_TYPE;
import cn.huhst.cas.weisiqian.pojo.Comment;
import cn.huhst.cas.weisiqian.pojo.News;
import cn.huhst.cas.weisiqian.service.NewsService;
import cn.huhst.cas.weisiqian.util.JSON;

@WebServlet("/ViewNews.do")
public class ViewNews extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(ViewNews.class);
	private NewsService newsservice = null;

	public ViewNews() {
		super();
		newsservice = new NewsService();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String newsid = request.getParameter("newsid");
		HttpSession session = request.getSession();
		if (newsid == null) {
			News news = (News) session.getAttribute("news");
			if (news != null) {
				newsid = news.getNewsid() + "";
			}
		}
		JSON json = new JSON();
		logger.info("newsid=" + newsid);
		if (newsid != null && !"".equals(newsid)) {
			News news = newsservice.getNewsByNewsID(newsid);
			if (news != null) {
				session.setAttribute("news", news);
				logger.info("获取新闻：" + news.getTitle() + "成功");
				ArrayList<Comment> comments = newsservice.getComment(news.getNewsid(), COMMENT_TYPE.NEWS_COMMENT);
				if (comments != null) {
					session.setAttribute("comments", comments);
					logger.info("浏览新闻：" + news.getTitle());
					json.putOKMSG("获取新闻成功");
				} else {
					logger.error("获取新闻评论失败");
					json.putErrorMSG("获取新闻评论失败");
				}
			} else {
				logger.error("获取新闻：" + newsid + " 出错");
				json.putErrorMSG("获取新闻失败");
			}
		} else {
			logger.error("要浏览的新闻的新闻ID为空");
			json.putErrorMSG("新闻ID有误");
		}

		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(json);
	}

}
